package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.MobileOrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.vo.OrderSubmit;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.MobileOrderService;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/mobile/order")
@Slf4j
public class MobileOrderController {
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MobileOrderService mobileOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderSettingService orderSettingService;



    @PostMapping("/submit")
    @Transactional
    public Result submit(@RequestBody OrderSubmit orderSubmit) {
        log.info("体检预约");
        log.info("orderSubmit:" + orderSubmit);

        String telephone = orderSubmit.getTelephone();
        //获取验证码
        String code = redisTemplate.opsForValue().get(telephone).toString();
        //判断验证码是否为空并且值是否相等
        if (StringUtils.isEmpty(orderSubmit.getValidateCode()) || !code.equals(orderSubmit.getValidateCode())) {
            throw new BusinessRuntimeException("验证码有误");
        }

        //获取预约日期
        Date orderDate = orderSubmit.getOrderDate();
        //根据预约日期查询预约设置
        OrderSetting orderSetting = orderSettingService.getOrderSettingByDate(orderDate);
        //判断 预约设置 对象是否为空 所选日期不能进行体检预约
        if (StringUtils.isEmpty(orderSetting)) {
            return new Result(false, MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        //判断预约设置的 已预约人数大于或等于可预约人数 预约已满
        if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            return new Result(false, MessageConst.ORDER_FULL);
        }

        String name = orderSubmit.getName();
        String idCard = orderSubmit.getIdCard();
        //根据电话查询会员表
        Member member = memberService.selectByPhoneNumber(telephone);
        //如果没查到就新增
        if (StringUtils.isEmpty(member)) {
            member = new Member();
            member.setName(name);
            member.setIdCard(idCard);
            member.setPhoneNumber(telephone);
            member.setRegTime(new java.sql.Date(new Date().getTime()));
            memberService.insert(member);
        }

        //根据会员id查询体检预约信息
        List<Order> orders = mobileOrderService.getOrderByMemberId(member.getId());

        Integer setmealId = orderSubmit.getSetmealId();
        //判断 orders 是否为空
        if (!StringUtils.isEmpty(orders)) {
            //遍历orders
            for (Order order : orders) {
                //判断每个order的预约日期和体检套餐id是否相等  已经完成预约，不能重复预约
                if (order.getOrderDate().equals(orderDate) && order.getSetmealId().equals(setmealId)) {
                    return new Result(false, MessageConst.HAS_ORDERED);
                }
            }
        }
        //预约日期的预约人数加1
        orderSettingService.updateReservationsAddOne(orderDate);

        //新建 order 对象
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(orderDate);
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(setmealId);
        //添加体检预约信息
        mobileOrderService.insert(order);

        return new Result(true, MessageConst.ORDER_SUCCESS,order);
    }

    @GetMapping("/findById")
    public Result findById(Integer id){
        //套餐
        Order order = mobileOrderService.findById(id);
        Member member = memberService.findById(order.getMemberId());
        Setmeal setmeal = setMealService.findById(order.getSetmealId());


        //返回结果封装
        Map<String,Object> map = new HashMap<>();
        map.put("member",member.getName());
        map.put("setmeal",setmeal.getName());
        map.put("orderDate",new SimpleDateFormat("yyyy-MM-dd").format(order.getOrderDate()));
        map.put("orderType",order.getOrderType());
        return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,map);
    }
}
